import React, { useRef, useState } from "react";
import { Button, Modal, Space, message } from "antd";
import { PlusOutlined } from '@ant-design/icons';
import { ProColumnType, ProTable } from "@ant-design/pro-components";
import { serviceTypes  } from "@/constants/types";
import { fetchServiceProviderList, addServiceProvider, updateServiceProvider, delServiceProvider } from "../services";
import { useRequest } from "ahooks";
import ServiceCreateModal from "../modals/ServiceCreateModal";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";
import { useModel } from "@umijs/max";
 
const Service = () => {
  const tableRef = useRef();
  const { getDict }  = useModel('dictModel');
  const [visible, setVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<serviceTypes | null>(null);
  const {loading: addLoading, runAsync: addApi} = useRequest(addServiceProvider, {manual: true});
  const {loading: updateLoading, runAsync: updateApi} = useRequest(updateServiceProvider, {manual: true});
  const serviceProviders = getDict('serviceProvider');

  const serviceProps = {
    title: currentRow ? '编辑服务商' : '新增服务商',
    visible,
    loading: addLoading || updateLoading,
    currentRow,
    onSubmit: async (params: serviceTypes) => {
      const apiFunc = currentRow ? updateApi : addApi;
      const res = await apiFunc(currentRow ? {
        ...params, 
        id: currentRow?.id
      } : params);
      if (res.code === '0') {
        message.success('操作成功');
        setVisible(false);
        setCurrentRow(null);
        tableRef?.current?.reload();
      }
    },
    onCancel: () => {
      setVisible(false);
      setCurrentRow(null);
    }
  }

  const handleCreate = () => {
    setVisible(true);
  }
  const handleUpdate = (row: serviceTypes) => {
    setCurrentRow(row);
    setVisible(true);
  }
  const handleDelete = (row: serviceTypes) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定删除？',
      onOk: () => {
        delServiceProvider({id: row.id}).then(res => {
          setVisible(false);
          setCurrentRow(null);
          tableRef?.current?.reload();
        })
      }
    });
  }

  const columns: ProColumnType<serviceTypes> [] = [
    {
      title: '类型',
      dataIndex: 'type',
      valueType: 'select',
      fieldProps: {
        options: serviceProviders
      },
      render: (_, record: serviceTypes) => <XlTableDictColumn type="serviceProvider" value={record?.type} />
    },
    {
      title: '公司名称',
      search: false,
      dataIndex: 'fullName'
    },
    {
      title: '公司简称',
      dataIndex: 'name'
    },
    {
      title: '英文简称',
      search: false,
      dataIndex: 'code'
    },
    {
      title: '创建时间',
      search: false,
      dataIndex: 'createTime'
    },
    {
      title: '操作',
      dataIndex: 'options',
      search: false,
      width: 200,
      render: (_, record: serviceTypes) => {
        return (
          <Space>
            <Button type="link" onClick={() => handleUpdate(record)}>编辑</Button>
            <Button type="link" onClick={() => handleDelete(record)}>删除</Button>
          </Space>
        );
      }
    }
  ];

  return (
    <> 
      <ProTable
        rowKey="id"
        bordered
        actionRef={tableRef}
        options={false}
        columns={columns}
        toolBarRender={() => [
          <Button onClick={handleCreate} type="primary">
            <PlusOutlined />
            新建
          </Button>
        ]}
        scroll={{y: 400}}
        request={async (params = {}, sort, filter) => {
          console.log(sort, filter);
          params.pageNum = params.current;
          const res = await fetchServiceProviderList({
            pageNum: params.current,
            pageSize: params.pageSize,
            type: params.type,
            name: params.name
          });
          return {
            data: res.data || [],
            total: res.total || 0,
            success: true
          }
        }}
      />
      {visible && <ServiceCreateModal {...serviceProps} />}
    </>
  );
};


export default Service;